<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" :close-on-press-escape="false" :close-on-click-modal="false" center>
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="first">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="specialty-form" @submit.prevent="handleSubmit">
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入商品名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品编码" prop="code">
                  <el-input v-model="formData.code" placeholder="请输入商品编码" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产地" prop="origin">
                  <el-input v-model="formData.origin" placeholder="请输入产地" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="isEnabled">
                  <el-switch v-model="formData.isEnabled" active-text="启用" inactive-text="禁用" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 价格信息 -->
          <div class="form-section">
            <h3 class="section-title">价格信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="原价" prop="originalPrice">
                  <el-input-number v-model="formData.originalPrice" :min="0" :precision="2" placeholder="请输入原价" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="现价" prop="price">
                  <el-input-number v-model="formData.price" :min="0" :precision="2" placeholder="请输入现价" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 产品信息 -->
          <div class="form-section">
            <h3 class="section-title">产品信息</h3>

            <el-form-item label="商品标签" prop="tagsJson">
              <div class="tags-container">
                <el-tag v-for="tag in formData.tagsJson" :key="tag" closable @close="removeTag(tag)" class="tag-item">
                  {{ tag }}
                </el-tag>
                <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" class="tag-input" />
                <el-button v-else size="small" @click="showInput" class="add-tag-btn"> + 添加标签 </el-button>
              </div>
            </el-form-item>

            <el-form-item label="产品描述" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入产品描述" />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="生产日期" prop="productionDate">
                  <el-date-picker v-model="formData.productionDate" type="date" placeholder="选择生产日期" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保质期(天)" prop="expirationDays">
                  <el-input-number v-model="formData.expirationDays" :min="1" placeholder="请输入保质期天数" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="评分" prop="rating">
                  <el-rate v-model="formData.rating" :max="5" allow-half show-score />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销量" prop="saleCount">
                  <el-input-number v-model="formData.saleCount" :min="0" placeholder="销量" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="orderNum">
                  <el-input-number v-model="formData.orderNum" :min="0" placeholder="排序" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 产品图片 -->
          <div class="form-section">
            <h3 class="section-title">产品图片</h3>
            <el-form-item label="产品图片" prop="imageUrls">
              <el-upload :file-list="imageFileList" :headers="fileHeader" :action="formAction" list-type="picture-card" :on-success="handleImageUpload" :on-remove="handleImageRemove">
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="主图" prop="imageUrls">
              <el-input v-model="faceIndex" :min="0" placeholder="主图文件索引" style="width: 100%">
                <template #append>
                  <el-button @click="handleSetFaceIndex">设置主图</el-button>
                </template>
              </el-input>
            </el-form-item>
          </div>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="商品详情" name="detail">
        <div class="editor">
          <div id="editProductToolbar"></div>
          <div id="editProductContainer"></div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布商品' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onBeforeUnmount, defineEmits, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/apis/product'
import type { FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus'

import '@wangeditor/editor/dist/css/style.css'
import { createEditor, createToolbar } from '@wangeditor/editor'
import type { IEditorConfig } from '@wangeditor/editor'

import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const user = computed(() => userStore.userInfo)
// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()

const submitting = ref(false)
const host = import.meta.env.VITE_BASE_URL

const formAction = ref(host + '/api/sysFile/uploadFile')
const fileHeader = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
})
const imageUrls = new Array()
const imageFileList = ref<UploadFile[]>([])
// 表单数据
const formData = ref({
  name: '',
  code: '',
  origin: '东川区',
  originalPrice: 100,
  price: 10,
  tagsJson: ['熟食'],
  description: '地道本地风味，选用优质食材。',
  productionDate: dayjs().format('YYYY-MM-DD'),
  expirationDays: 7,
  isEnabled: true,
  imageUrls: '',
  htmlContent: '',
  saleCount: 10,
  orderNum: 100,
  rating: 5
})

// 标签相关
const inputVisible = ref(false)
const inputValue = ref('')

const handleImageUpload = (response: any) => {
  // console.log('Logo上传结果:', response)
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}`
    imageUrls.push(url)
    ElMessage.success('上传成功')
    // console.log('上传成功', url)
  } else {
    ElMessage.error('Logo上传失败: ' + response.message)
  }
}
const faceIndex = ref(1)

const handleSetFaceIndex = () => {
  let index = faceIndex.value - 1
  let url = imageUrls[index]
  imageUrls.splice(index, 1)
  // console.log(JSON.stringify(imageUrls))
  imageUrls.splice(0x00, 0, url)
  // console.log(JSON.stringify(imageUrls))
  ElMessage.success('更新成功')
}

const handleImageRemove = (file: any) => {
  const currentImages = JSON.parse(formData.value.imageUrls || '[]')
  const index = imageFileList.value.findIndex((item) => item.uid === file.uid)
  imageUrls.splice(index, 1)
  if (index > -1) {
    currentImages.splice(index, 1)
    formData.value.imageUrls = JSON.stringify(currentImages)
  }
}

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  origin: [{ required: true, message: '请输入产地', trigger: 'blur' }],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0, message: '原价必须大于等于0', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入现价', trigger: 'blur' },
    { type: 'number', min: 0, message: '现价必须大于等于0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入产品描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  productionDate: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
  expirationDays: [
    { required: true, message: '请输入保质期天数', trigger: 'blur' },
    { type: 'number', min: 1, message: '保质期必须大于0天', trigger: 'blur' }
  ]
}

const removeTag = (tag: string) => {
  const index = formData.value.tagsJson.indexOf(tag)
  if (index > -1) {
    formData.value.tagsJson.splice(index, 1)
  }
}
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !formData.value.tagsJson.includes(inputValue.value)) {
    formData.value.tagsJson.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 表单操作方法
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证价格逻辑
    if (formData.value.price > formData.value.originalPrice) {
      ElMessage.warning('现价不能高于原价')
      return
    }

    const submitData = { ...formData.value }
    submitData.imageUrls = JSON.stringify(imageUrls)
    http
      .create(submitData)
      .then((response) => {
        const { code, message } = response.data
        if (code !== 200) {
          throw new Error(message || '提交失败')
        }
        ElMessage.success('商品信息保存成功！')
        // 重置表单
        formRef.value?.resetFields()
      })
      .catch((error) => {
        ElMessage.error(error.message || '提交失败，请稍后再试')
      })
    // console.log('提交数据:', submitData)
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value,
      tagsJson: ''
    }
    submitData.tagsJson = JSON.stringify(formData.value.tagsJson)
    submitData.imageUrls = JSON.stringify(imageUrls)
    submitData.htmlContent = editor.getHtml()
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}

const activeName = ref('first')

type InsertFnType = (url: string, alt: string, href: string) => void
const editorConfig: Partial<IEditorConfig> = {
  MENU_CONF: {
    uploadImage: {
      server: host + '/api/sysFile/uploadFile',
      fieldName: 'file',
      base64LimitSize: 5 * 1024, // 小于该值就插入 base64 格式（而不上传），默认为 0
      meta: {
        path: 'news'
      },
      // 自定义增加 http  header
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      onSuccess(file: File, res: any) {
        // TS 语法
        // onSuccess(file, res) {          // JS 语法
        // console.log(`${file.name} 上传成功`, res)
      },
      // 自定义插入图片
      customInsert(res: any, insertFn: InsertFnType) {
        // res 即服务端的返回结果
        let { code, message, result } = res
        if (code != 200) {
          ElMessage.error(message)
          return
        }
        let url = host + '/' + result.url
        // console.log(res)
        let [alt, href] = [result.fileName, url]
        // console.log(url, alt, href)
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(url, alt, href)
      }
    }
  }
}
let editor: any = null

onBeforeUnmount(() => {
  console.log('remove editor ')
  editor && editor.destroy()
})

const handleCreateEditor = (html: string) => {
  if (editor) {
    editor.setHtml(html)
    return
  }
  // 创建编辑器
  editor = createEditor({
    selector: '#editProductContainer',
    html: html,
    config: editorConfig,
    mode: 'default' // or 'simple'
  })
  // 创建工具栏
  const toolbar = createToolbar({
    editor,
    selector: '#editProductToolbar'
  })
  if (window.hasOwnProperty('editor')) {
    return
  }
  Object.defineProperty(window, 'editor', {
    get() {
      return editor
    }
  })
  // console.log(editor)
}

const dialogTitle = ref('新增数据')
const emit = defineEmits(['update', 'create'])
const editMode = ref(false)
const dialogVisible = ref(false)
const handleCreate = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false
  imageFileList.value = []
  imageUrls.splice(0x00, imageUrls.length)
  formData.value = {
    name: '',
    code: '',
    htmlContent: '',
    origin: '东川区',
    originalPrice: 0,
    price: 0,
    tagsJson: ['熟食'],
    description: '',
    productionDate: dayjs().format('YYYY-MM-DD'),
    expirationDays: 7,
    isEnabled: true,
    imageUrls: '',
    saleCount: 10,
    orderNum: 100,
    rating: 5
  }

  nextTick(() => {
    handleCreateEditor('')
  })
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'
  imageFileList.value = []
  formData.value.tagsJson = JSON.parse(obj.tagsJson)
  imageUrls.splice(0x00, imageUrls.length)

  nextTick(() => {
    handleCreateEditor(obj.htmlContent || '')
  })
  if (!obj.imageUrls) {
    return
  }
  let imgs = JSON.parse(obj.imageUrls)

  imgs.forEach((t: string, index: number) => {
    imageUrls.push(t)
    imageFileList.value.push({ url: t, uid: 100 + index, status: 'success', name: 'file_' + index })
  })
  //   console.log(obj)
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  display: flex;
  flex-wrap: wrap;
}

.form-section {
  margin: 10px 10px;
  flex: 1 1;
  min-width: 400px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}
.tags-container {
  display: flex;
  gap: 10px;
}
.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.editor {
  height: auto;
  border: 1px solid #ccc;
}
#editProductToolbar {
  height: auto;
}
#editProductContainer {
  height: 50vh;
}
</style>
